package org.secangkirkopipanas.gxtcore.server.dao.impl;

import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.secangkirkopipanas.gxtcore.common.exception.DataNotFoundException;
import org.secangkirkopipanas.gxtcore.server.dao.ISystemUserDAO;
import org.secangkirkopipanas.gxtcore.server.domain.SystemGroup;
import org.secangkirkopipanas.gxtcore.server.domain.SystemUser;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class SystemUserDAO implements ISystemUserDAO {

	private SessionFactory sessionFactory;

	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Transactional(propagation = Propagation.SUPPORTS)
	public SystemUser get(String username) {
		return (SystemUser) sessionFactory.getCurrentSession().createCriteria(
				SystemUser.class).add(Restrictions.eq("username", username))
				.uniqueResult();
	}

	@Transactional(propagation = Propagation.SUPPORTS)
	public SystemUser get(String username, String pwdDigest) {
		return (SystemUser) sessionFactory.getCurrentSession().createCriteria(
				SystemUser.class).add(Restrictions.eq("username", username))
				.add(Restrictions.eq("pwdDigest", pwdDigest)).uniqueResult();
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation = Propagation.SUPPORTS)
	public List<SystemUser> getForList() {
		return sessionFactory.getCurrentSession().createCriteria(
				SystemUser.class).list();
	}

	@Transactional(propagation = Propagation.SUPPORTS)
	public int getTotalCount() {
		return (Integer) sessionFactory.getCurrentSession().createCriteria(
				SystemGroup.class).setProjection(Projections.rowCount()).list()
				.get(0);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void add(SystemUser systemUser) {
		sessionFactory.getCurrentSession().saveOrUpdate(systemUser);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void delete(SystemUser systemUser) throws DataNotFoundException {
		SystemUser systemUserFound = get(systemUser.getUsername());
		if (systemUserFound != null) {
			sessionFactory.getCurrentSession().delete(systemUser);
		} else {
			throw new DataNotFoundException("User with username '"
					+ systemUser.getUsername() + "' is not found");
		}
	}

	@Transactional(propagation = Propagation.REQUIRED)
	public void delete(String username) throws DataNotFoundException {
		SystemUser systemUserFound = get(username);
		if (systemUserFound != null) {
			sessionFactory.getCurrentSession().delete(systemUserFound);
		} else {
			throw new DataNotFoundException("User with username '" + username
					+ "' is not found");
		}
	}

}